package com.tianhui.consignortwofei.mvp.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.PopupWindow;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.PoiItemV2;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.poisearch.PoiResultV2;
import com.amap.api.services.poisearch.PoiSearchV2;
import com.baidu.mapapi.model.LatLng;

import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonView;
import com.fgs.common.entity.region.RegionInfo;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.ToastUtil;
import com.fgs.common.widget.itemView.CitySearchView;
import com.fgs.common.widget.itemView.InputItemView;

import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.mvp.model.enty.SourcePathInfo;
import com.tianhui.consignortwofei.mvp.ui.adapter.PopDressGaoDeListAdapter;

import org.greenrobot.eventbus.EventBus;
import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/4/28
 * @description
 **/
public class SelectDressActivity extends BaseActivity implements PoiSearchV2.OnPoiSearchListener {

    @BindView(R.id.csv_zhuanghuo)
    CitySearchView csv_zhuanghuo;
    @BindView(R.id.inpiv_zhuanghuo)
    InputItemView inpiv_zhuanghuo;
//    @BindView(R.id.activity_about_updateLinearLayout)
//    LinearLayout mUpdateLinearLayout;

    @BindView(R.id.lv_dress)
    RecyclerView lv_dress;


    private PopupWindow dressPopup;
    private PopDressGaoDeListAdapter dressListAdapter;
    private List<SuggestionResult.SuggestionInfo> allSuggestions;
    private List<PoiItemV2> poiResultsList;
    private boolean openPop=true;
    private int whitchSet=1;
//    private PoiSearch mPoiSearch;
        private SuggestionSearch mSuggestionSearch;


    @Override
    public int getLayoutId() {
        return R.layout.activity_select_dress;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public void init() {
        setTitle("选择地址");

        Bundle bundle = getIntent().getExtras();
        whitchSet=bundle.getInt(KeyValue.KEY_TYPE,2);

        initView();

    }

    @Override
    public BaseFragment createFragment() {
        return null;
    }

    @OnClick(R.id.tv_true)
    public void selectTrue() {
        String city = csv_zhuanghuo.getContent();
        String address = inpiv_zhuanghuo.getContent();
        try {
            if (null==zhuangHuoDress.placecounty){
                showToast("请选择区，再点确定");
                return;
            }
        }catch (Exception e){
            LogUtil.print(e.toString());
        }
        if (TextUtils.isEmpty(city)){
            ToastUtil.showShortToast("请先选择省市区");
        }else {
            if (null==zhuangHuoDress){
                ToastUtil.showShortToast("请选择完整省市县");
            }else {
                zhuangHuoDress.whitchSet= whitchSet;
                zhuangHuoDress.shuAddress=address;
                EventBus.getDefault().post(zhuangHuoDress);
                finish();
            }

        }

    }

    @OnClick(R.id.tv_false)
    public void selectFalse() {
//        csv_zhuanghuo.setContent("");
        inpiv_zhuanghuo.setContent("");
        dressListAdapter.removeAll();
    }





    private void initView() {


        csv_zhuanghuo.setTitle("城市/区域");
        csv_zhuanghuo.setContentHint("必填，请输入或选择省市区");
//        mDestinationCitySearchView.setTitle("目的地");
//        mDestinationCitySearchView.setContentHint("请输入或选择目的地");

        csv_zhuanghuo.setOnCitySearchListener(new CitySearchView.OnCitySearchListener() {
            @Override
            public void citySearchCallback(RegionInfo regionInfo) {
                SourcePathInfo sourcePathInfo = new SourcePathInfo();
                sourcePathInfo.placeprovince = regionInfo.province;
                sourcePathInfo.placecity = regionInfo.city;
                sourcePathInfo.placecounty = regionInfo.county;
                sourcePathInfo.placecitycode = regionInfo.code;
                sourcePathInfo.placeparentcode = regionInfo.parentcode;
                setSelectPathInfo(KeyValue.RESULT_DELIVER, sourcePathInfo, true);

            }
        });

        csv_zhuanghuo.setOnCitySearchSelectListener(new CitySearchView.OnCitySearchSelectListener() {
            @Override
            public void onCitySelect(RegionInfo regionInfo) {
                SourcePathInfo sourcePathInfo = new SourcePathInfo();
                sourcePathInfo.placeprovince = regionInfo.province;
                sourcePathInfo.placecity = regionInfo.city;
                sourcePathInfo.placecounty = regionInfo.county;
                sourcePathInfo.placecitycode = regionInfo.code;
                sourcePathInfo.placeparentcode = regionInfo.parentcode;
                setSelectPathInfo(KeyValue.RESULT_DELIVER, sourcePathInfo, false);
            }
        });



        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lv_dress.setLayoutManager(linearLayoutManager);
        dressListAdapter = new PopDressGaoDeListAdapter(this);
        lv_dress.setAdapter(dressListAdapter);

        if (poiResultsList != null ) {//&& mConsignorList.size() > 0
            dressListAdapter.addAll(poiResultsList);
        }

        dressListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                try {
                    openPop=false;
                    Object object = dressListAdapter.getAllData().get(position);
//                    if (object != null && object instanceof SuggestionResult.SuggestionInfo) {
                    PoiItemV2 info = (PoiItemV2) object;
//                        if (1==whitchSet) {
                            inpiv_zhuanghuo.setContent(info.getTitle());

                            if (null!=zhuangHuoDress){
//                                double latitude = info.getLatLonPoint().getLatitude();
//                                double longitude = info.getLatLonPoint().getLongitude();

                                LatLng latLng=new LatLng(info.getLatLonPoint().getLatitude(),
                                        info.getLatLonPoint().getLongitude());
                                zhuangHuoDress.latLng=latLng;


                            }else {
                                SourcePathInfo sourcePathInfo = new SourcePathInfo();
                                sourcePathInfo.placeprovince = info.getProvinceName();
                                sourcePathInfo.placecity = info.getCityName();
                                sourcePathInfo.placecounty = info.getAdName();
                                sourcePathInfo.placecitycode = info.getAdCode();
                                sourcePathInfo.placeparentcode = info.getAdCode();
                                setSelectPathInfo(KeyValue.RESULT_DELIVER, sourcePathInfo, true);

                                LatLng latLng=new LatLng(info.getLatLonPoint().getLatitude(),
                                        info.getLatLonPoint().getLongitude());
                                zhuangHuoDress.latLng=latLng;
                            }

//                        }else {
//                            mDestinationAddressInputItemView.setContent(info.getKey());
//                        }
//                        dressPopup.dismiss();
//                    }
                }catch (Exception e){
                    LogUtil.print(e.toString());
                }

            }
        });

        allSuggestions=new ArrayList<>();
        poiResultsList=new ArrayList<>();

//        mPoiSearch = PoiSearch.newInstance();
//        OnGetPoiSearchResultListener listener = new OnGetPoiSearchResultListener() {
//            @Override
//            public void onGetPoiResult(PoiResult poiResult) {
//                List<PoiInfo> allPoi = poiResult.getAllPoi();
//                List<PoiAddrInfo> allAddr = poiResult.getAllAddr();
////                if (null!=suggestionResult.getAllSuggestions()&&suggestionResult.getAllSuggestions().size()>0) {
////                    SelectDressActivity.this.allSuggestions.clear();
////                    SelectDressActivity.this.allSuggestions.addAll(suggestionResult.getAllSuggestions());
////                    dressListAdapter.removeAll();
////                    dressListAdapter.addAll(SelectDressActivity.this.allSuggestions);
////                }
//
//
//            }
//            @Override
//            public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
//                List<PoiDetailInfo> poiDetailInfoList = poiDetailSearchResult.getPoiDetailInfoList();
//            }
//            @Override
//            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {
//                List<PoiIndoorInfo> arrayPoiInfo = poiIndoorResult.getArrayPoiInfo();
//
//            }
//            //废弃
//            @Override
//            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
//
//            }
//        };
//        mPoiSearch.setOnGetPoiSearchResultListener(listener);


        ServiceSettings.updatePrivacyShow(this,true,true);
        ServiceSettings.updatePrivacyAgree(this,true);



//        //百度poi搜索
//        mSuggestionSearch = SuggestionSearch.newInstance();
//        OnGetSuggestionResultListener listener = new OnGetSuggestionResultListener() {
//            @Override
//            public void onGetSuggestionResult(SuggestionResult suggestionResult) {
//                //处理sug检索结果
//                if (null!=suggestionResult.getAllSuggestions()&&suggestionResult.getAllSuggestions().size()>0) {
////                    SelectDressActivity.this.allSuggestions.clear();
////                    SelectDressActivity.this.allSuggestions.addAll(suggestionResult.getAllSuggestions());
////                    dressListAdapter.removeAll();
////                    dressListAdapter.addAll(SelectDressActivity.this.allSuggestions);
//                }
//
//            }
//        };
//        mSuggestionSearch.setOnGetSuggestionResultListener(listener);
//
//        mSuggestionSearch.requestSuggestion(new SuggestionSearchOption()
//                         .city("北京")
//                         .keyword("肯"));




        //装货详细地址
        inpiv_zhuanghuo.setOnInputItemListener(new InputItemView.OnInputItemListener() {
            @Override
            public void onInput(String string) {
                if (openPop) {
                    if (!TextUtils.isEmpty(string)) {
//                        whitchSet=1;
//                    } else {

//                        String city = csv_zhuanghuo.getContent();
//                        if (TextUtils.isEmpty(city)){
//                            ToastUtil.showShortToast("请先选择省市区");
//                        }else {
                        String placecity="";
                        if (null!=zhuangHuoDress) {
                            placecity = zhuangHuoDress.placecity;
                        }
                            /**
                             * 在您的项目中，keyword为随您的输入变化的值
                             */
//                            mSuggestionSearch.requestSuggestion(new SuggestionSearchOption()
//                                    .city(placecity)
//                                    .keyword(string));
////                                    .city("北京")
////                                    .keyword("肯"));

//                            mPoiSearch.searchInCity(new PoiCitySearchOption()
//                                    .city("北京") //必填
//                                    .keyword("美食") //必填
//                                    .pageNum(0));


                            //高德地图
                            PoiSearchV2.Query query = new PoiSearchV2.Query(string, "", placecity);
                            //keyWord表示搜索字符串，
                            //第二个参数表示POI搜索类型，二者选填其一，选用POI搜索类型时建议填写类型代码，码表可以参考下方（而非文字）
                            //cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
                            query.setPageSize(20);// 设置每页最多返回多少条poiitem
                            query.setPageNum(0);//设置查询页码

                            try {
                                PoiSearchV2  poiSearch = new PoiSearchV2(SelectDressActivity.this, query);
                                poiSearch.setOnPoiSearchListener(SelectDressActivity.this);
                                poiSearch.searchPOIAsyn();
                            } catch (AMapException e) {
                                e.printStackTrace();
                            }





//                        }

                    }
                }else {
                    openPop=true;
                }

            }
        });



    }





    SourcePathInfo zhuangHuoDress;
    private void setSelectPathInfo(int resultCode, SourcePathInfo pathInfo, boolean isNeedReprocessingPathInfo) {
            csv_zhuanghuo.setIsNeedFilterCity(isNeedReprocessingPathInfo);
            pathInfo.address=pathInfo.placeprovince+" "+pathInfo.placecity+" "+pathInfo.placecounty;
            csv_zhuanghuo.setContent(pathInfo.address);
            zhuangHuoDress=pathInfo;
            zhuangHuoDress.isWhereGet=isNeedReprocessingPathInfo;

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mPoiSearch.destroy();
    }

    @Override
    public void onPoiSearched(PoiResultV2 poiResultV2, int i) {
        ArrayList<PoiItemV2> pois = poiResultV2.getPois();
        if (null!=pois&&pois.size()>0) {
            SelectDressActivity.this.poiResultsList.clear();
            SelectDressActivity.this.poiResultsList.addAll(pois);
            dressListAdapter.removeAll();
            dressListAdapter.addAll(SelectDressActivity.this.poiResultsList);

        }
    }

    @Override
    public void onPoiItemSearched(PoiItemV2 poiItemV2, int i) {
//        List<SubPoiItemV2> subPois = poiItemV2.getSubPois();
    }
}
